package com.jianyun.jyzs.widget;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;


/**
 * Created by AMing on 17/8/9.
 * Company RongCloud
 * 为解决 pin 详情点击空白或者滑动收起软键盘还要不影响 RongExtension 重写的 ScrollView
 */

public class PinScrollView extends ScrollView {
    private OnScrollListener onScrollListener;

    private int lastScrollY;

    public PinScrollView(Context context) {
        this(context, null);
    }

    public PinScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PinScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 设置滚动接口
     *
     * @param onScrollListener
     */
    public void setOnScrollListener(OnScrollListener onScrollListener) {
        this.onScrollListener = onScrollListener;
    }


    /**
     * 用于用户手指离开 PinScrollView 的时候获取 PinScrollView 滚动的Y距离，然后回调给onScroll方法中
     */
    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            int scrollY = PinScrollView.this.getScrollY();

            if (lastScrollY != scrollY) {
                lastScrollY = scrollY;
                handler.sendMessageDelayed(handler.obtainMessage(), 5);
            }
            if (onScrollListener != null) {
                onScrollListener.onScroll(scrollY);
            }

        }

        ;

    };


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (onScrollListener != null) {
            onScrollListener.onScroll(lastScrollY = this.getScrollY());
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_UP:
                handler.sendMessageDelayed(handler.obtainMessage(), 5);
                break;
        }
        return super.onTouchEvent(ev);
    }


    /**
     * 滚动的回调接口
     *
     * @author xiaanming
     */
    public interface OnScrollListener {
        /**
         * 回调方法， 返回 PinScrollView 滑动的Y方向距离
         *
         * @param scrollY
         */
         void onScroll(int scrollY);
    }


}
